import logging
import socket
import requests

logger = logging.getLogger(__name__)


class IpUtil:
    """IP工具类"""

    @staticmethod
    def get_host_name() -> str:
        """获取本地IP地址"""
        return socket.gethostname()

    @staticmethod
    def get_host_ip() -> str:
        """获取本地主机名"""
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('10.0.0.0', 0))
            ip = s.getsockname()[0]
        except Exception as _:
            ip = '127.0.0.1'
        finally:
            s.close()
        return ip

    @staticmethod
    def get_local_ip() -> str:
        """获取本地局域网 IP 地址"""
        try:
            # 获取主机名对应的 IP
            ip = socket.gethostbyname(socket.gethostname())
            # 检查是否是有效的局域网地址
            if ip.startswith("127.") or ip == "0.0.0.0":
                raise ValueError("IP 无效，可能没有联网")
        except Exception:
            # 获取局域网 IP 的备用方法，适用于不同的网络环境
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            try:
                # 使用局域网中的任意地址来测试，通常是可以连通的
                s.connect(('10.255.255.255', 1))
                ip = s.getsockname()[0]
            except Exception:
                ip = '127.0.0.1'  # 无法获取局域网 IP 时返回 localhost
            finally:
                s.close()
        return ip

    @staticmethod
    def get_external_ip() -> str:
        """获取外网IP地址"""
        try:
            # 使用外部服务获取公共IP
            response = requests.get('https://api.ipify.org?format=json')
            ip = response.json().get('ip')
        except Exception as e:
            # 如果获取外网IP失败，记录错误并返回None
            logger.error(f"获取外网IP地址失败: {e}")
            ip = None
        return ip
